const COS = require("cos-nodejs-sdk-v5");
const fs = require("fs");
const path = require("path");

const pluginName = 'CosBuildWebpackPlugin';
// 云产品Id和Key
const SecretId = 'AKID2xghejpqmibS9cxBGBwYxAlIl24rPiog';
const SecretKey = 'seDbkfMuOpGZigSgv56yjKpFbp03xfMt';
// 云产品存储桶名和地区
const Bucket = 'webpack-1322236839';
const Region = 'ap-guangzhou';

const cos = new COS({
  SecretId,
  SecretKey,
});
// 检测桶是否存在
function doesBucketExist() {
  return new Promise((resolve, reject) => {
    cos.headBucket(
      {
        Bucket,
        Region,
      },
      function (err, data) {
        if (data) {
          console.log("存储桶存在");
          cos.getBucket(
            {
              Bucket,
              Region,
            },
            function (err, data) {
              // console.log(err || data.Contents);
              resolve(data.Contents);
            }
          );
        } else if (err.statusCode == 404) {
          console.log("存储桶不存在");
          reject(data);
        } else if (err.statusCode == 403) {
          console.log("没有该存储桶读权限");
          reject(data);
        }
      }
    );
  });
}
// 上传对象
function putObject(filePath, filename) {
  cos.putObject(
    {
      Bucket,
      Region,
      Key: filename.replace(/\\/g, "/"),
      /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */ // StorageClass: 'STANDARD',
      /* 当 Body 为 stream 类型时，ContentLength 必传，否则 onProgress 不能返回正确的进度信息 */
      Body: fs.createReadStream(filePath), // 上传文件对象
      ContentLength: fs.statSync(filePath).size,
      // onProgress: function (progressData) {
      //   console.log(JSON.stringify(progressData));
      // },
    },

    function (err, data) {
      // console.log(err || data);
    }
  );
  console.log("123123", filename);
}
// 清空当前存储桶
function deleteMultipleObject(keysArr) {
  const objectsMap = keysArr.map((item) => ({ Key: item.Key }));
  return new Promise((resolve, reject) => {
    cos.deleteMultipleObject(
      {
        Bucket,
        Region,
        Objects: objectsMap,
      },
      function (err, data) {
        // console.log(err || data);
        if (err) reject(err);
        resolve(data);
      }
    );
  });
}

class CosBuildWebpackPlugin {
  apply(compiler) {
    // compiler.hooks 生命周期钩子函数
    // 正在编译的时候运行
    compiler.hooks.run.tap(pluginName, (compilation) => {
      console.log("webpack 构建正在启动!");
    });
    // 输出 asset 到 output 目录之后执行
    compiler.hooks.afterEmit.tapPromise(pluginName, async (compilation) => {
      // 获取输出目录（dist）的绝对路径
      const outputPath = compilation.outputOptions.path;

      // 获取所有生成的文件信息
      const assets = compilation.assets;

      console.log("webpack 构建完成!");
      const list = await doesBucketExist();
      if (list.length) {
        // 删除
        await deleteMultipleObject(list);
      }
      // 添加
      for (const filename in assets) {
        // 获取文件的绝对路径
        const absolutePath = path.join(outputPath, filename);
        // 打印文件路径
        // console.log('File Path:', absolutePath);
        putObject(absolutePath, filename);
      }
    });
  }
}

module.exports = CosBuildWebpackPlugin;
